package com.dlc.shop.user.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dlc.shop.bean.param.UserTagParam;
import com.dlc.shop.user.common.dao.UserTagMapper;
import com.dlc.shop.user.common.dao.UserTagUserMapper;
import com.dlc.shop.user.common.model.UserTag;
import com.dlc.shop.user.common.model.UserTagUser;
import com.dlc.shop.user.common.service.UserTagUserService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用户和标签关联表
 *
 * @author LGH
 * @date 2020-09-10 08:44:22
 */
@Service
@AllArgsConstructor
public class UserTagUserServiceImpl extends ServiceImpl<UserTagUserMapper, UserTagUser> implements UserTagUserService {

    private final UserTagUserMapper userTagUserMapper;
    private final UserTagMapper userTagMapper;

    @Override
    public UserTagUser getByUserIdAndTagId(String userId, Long tagId) {
        return userTagUserMapper.getByUserIdAndTagId(userId,tagId);
    }

    @Override
    public Integer countByUserIdAndTagId(String userId, Long tagId) {
        Integer count = userTagUserMapper.countByUserIdAndTagId(userId,tagId);
        return Objects.isNull(count)? 0 : count;
    }

    @Override
    public List<UserTagParam> getUserTagsUserByUserId(String userId) {
        List<UserTagParam> userTagParams = userTagUserMapper.getUserTagsUserByUserId(userId);
        return userTagParams;
    }

    @Override
    public Boolean removeByUserIdAndTagId(String userId, Long userTagId) {
        boolean a = userTagUserMapper.removeByUserIdAndTagId(userId,userTagId) > 0;
        Map<Long, Integer> tagUser = new HashMap<>(16);
        tagUser.put(userTagId,-1);
        userTagMapper.updateBatch(tagUser);
        return a;
    }

    @Override
    public List<UserTagParam> getUserShopTag(String userId, Long shopId) {
        return userTagUserMapper.getUserShopTag(userId, shopId);
    }

    @Override
    public void removeBatchShopTag(List<String> userIds, Integer tagCategory, Long shopId) {
        // 查询出当前店铺对应分类的所有手动标签
        List<UserTag> userTags = userTagMapper.selectList(new LambdaQueryWrapper<UserTag>()
                .eq(UserTag::getShopId, shopId)
                .eq(UserTag::getTagCategory, tagCategory)
                .eq(UserTag::getTagType, 0));
        if (CollectionUtils.isEmpty(userTags)) {
            return;
        }
        List<Long> tagIds = userTags.stream().map(UserTag::getUserTagId).collect(Collectors.toList());
        // in条件删除对应标签，用户的关联数据
        this.remove(new LambdaQueryWrapper<UserTagUser>()
                .in(UserTagUser::getUserTagId, tagIds)
                .in(UserTagUser::getUserId, userIds));
    }

}
